#include "stdafx.h"
#include "anim_actor.hpp"
#include <iostream>
#include <boost/any.hpp>
#include <boost/bind.hpp>

namespace FndGame2D {
  const std::string anim_actor::SET_ANIM_LOOP("anim_loop") ;
  const std::string anim_actor::SET_ANIM_SPEED("anim_speed") ;
  const std::string anim_actor::HAS_ANIM("has_anim") ;
  bool anim_actor::handle_set_anim_loop(const normal_thinker_message_type& msg) {
    try{
      set_anim_loop(boost::any_cast<bool>(msg.param)) ;
      return true; 
    } catch(const boost::bad_any_cast&) {
      return false ;
    }
  }
  bool anim_actor::handle_set_anim_speed(const normal_thinker_message_type& msg) {
    try {
      set_anim_speed(boost::any_cast<float>(msg.param)) ;
      return true ;
    } catch(const boost::bad_any_cast&) {
      return false ;
    }
  }
  anim_actor::anim_actor(const std::string& name, int draw_level,
			 const mover::position_type& pos,
			 float angle) :
    quad_actor(name, draw_level, pos, angle),
    m_current_anim_name(),
    m_anim_speed(0.0f),
    m_anim_looped(false),
    m_current_anim_index(0),
    m_current_anim_time(0.0f) {
    message_handler.add_handle(SET_ANIM_SPEED, boost::bind(&anim_actor::handle_set_anim_speed,
							   this, _1)) ;
    message_handler.add_handle(SET_ANIM_LOOP, boost::bind(&anim_actor::handle_set_anim_loop,
							  this, _1)) ;

    updater2.connect(sigc::mem_fun(this, &anim_actor::update_anim)) ;
    add_property<bool>(HAS_ANIM, true) ;
  }
  void anim_actor::set_anim(const std::string& anim_name) {

    if(!m_rects_mgr.has_index(anim_name)) return ;
   
    m_current_anim_name = anim_name ;
    m_current_anim_index = 0 ;
    set_current_rect() ;
  }

  void anim_actor::set_current_rect() {
    const sf::IntRect& rect = m_rects_mgr.get_value(m_current_anim_name,
						    m_current_anim_index) ;
    set_rect(rect) ;

  }
  void anim_actor::update_anim(float t) {
    if(m_anim_speed <= 0.0f) return ;
    m_current_anim_time += t ;
    if(m_current_anim_time >= m_anim_speed) {
      m_current_anim_time -= m_anim_speed ;
      m_current_anim_index++ ;
      if(m_current_anim_index >= 
	 m_rects_mgr.get_index_number(m_current_anim_name)) {
	if(m_anim_looped) m_current_anim_index = 0 ;
	else m_current_anim_index-- ;
      }
      set_current_rect() ;
    }
  }

}
